#!/usr/bin/env node

/*
 * Copyright 2013-2019 The NATS Authors
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* jslint node: true */
'use strict'

const nats = require('../')
const argv = require('minimist')(process.argv.slice(2))

const url = argv.s || nats.DEFAULT_URI
const creds = argv.creds
const queue = argv.queue
const subject = argv._[0]
const response = argv._[1] || ''

if (!subject) {
  console.log('Usage: node-rep  [-s server] [--creds=creds_file_path] [--queue=qname] <subject> [response]')
  process.exit()
}

// Connect to NATS server.
const nc = nats.connect(url, nats.creds(creds))

nc.on('connect', () => {
  const opts = {}
  if (queue) {
    opts.queue = queue
  }

  let count = 0
  nc.subscribe(subject, opts, (msg, reply) => {
    if (reply) {
      // give the response or echo back
      const d = response || msg
      nc.publish(reply, d)
      console.log('Sent [' + count++ + '] reply "' + d + '"')
      return
    }
    console.log('Dropping message "' + msg + '" - no reply subject set')
  })
  if (queue) {
    console.log('Queue reply [' + queue + '] listening on [' + subject + ']')
  } else {
    console.log('Reply listening on [' + subject + ']')
  }
})

nc.on('unsubscribe', () => {
  process.exit()
})

nc.on('error', (err) => {
  console.log('Error [' + nc.currentServer + ']: ' + err)
  process.exit()
})
